<template>
  <!-- 抽屉 -->
  <a-drawer placement="right" class="article-info" :width="800" :visible="visible" @close="onClose">
    <template #title>
      <div class="title">{{ title }}</div>
    </template>
    <a-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 14 }"
    >
      <a-form-item name="articleName" label="文章标题">
        <a-input v-model:value="formState.articleName">
          <template #suffix>
            {{ formState.articleName.length }}
            <span class="input-limit">/45</span>
          </template>
        </a-input>
      </a-form-item>

      <a-form-item label="标签" name="tags">
        <a-select
          show-search
          mode="multiple"
          v-model:value="formState.tags"
          :default-active-first-option="false"
          :show-arrow="false"
          :filter-option="false"
          :not-found-content="null"
          style="width: 100%"
          placeholder="请输入标签"
          option-label-prop="label"
          @search="confirmGetTagList"
          @focus="confirmGetTagList('')"
        >
          <a-select-option
            v-for="item in tags"
            :key="item.id"
            :value="item.id"
            :label="item.labelName"
          >
            <a-row type="flex" class="select-content">
              <a-col :span="12">
                <span>{{ item.labelName }}</span>
              </a-col>
              <a-col :span="12">
                <a-row type="flex" justify="end">
                  <a-dropdown @click.prevent>
                    <i class="icon-mulu-16 iconfont"></i>
                    <template #overlay>
                      <a-menu>
                        <a-menu-item>
                          <a href="javascript:;" @click="editTag(item)">编辑</a>
                        </a-menu-item>
                        <a-menu-item>
                          <a href="javascript:;" @click="delTag(item)">删除</a>
                        </a-menu-item>
                      </a-menu>
                    </template>
                  </a-dropdown>
                </a-row>
              </a-col>
            </a-row>
          </a-select-option>
        </a-select>
        <!-- 添加标签 -->
        <a-button type="primary" ghost @click="addTag">添加标签</a-button>
      </a-form-item>
      <a-form-item label="文章类型" name="articleType">
        <a-radio-group
          v-if="typeReadonly"
          disabled
          :value="formState.articleType"
          :options="options"
        />
        <a-radio-group v-else v-model:value="formState.articleType" :options="options" />
      </a-form-item>
      <a-form-item v-if="formState.articleType === 1" label="纯文字描述" name="describeInfo">
        <a-textarea
          v-model:value="formState.describeInfo"
          class="article-info_textarea"
          showCount
          :auto-size="{ minRows: 6, maxRows: 6 }"
          :rows="6"
          placeholder="请输入描述"
          :maxlength="100"
        />
        <div class="describeInfo-tips">
          纯文本描述主要用于客户后侧面弹窗的菜单帮助，若需要关联菜单帮助，请填写相关内容
        </div>
      </a-form-item>
      <a-form-item label="文章内容" name="articleInfo" v-if="formState.articleType === 1">
        <div style="width: 600px">
          <wang-editor ref="wangEditor" v-model:value="formState.articleInfo"></wang-editor>
        </div>
      </a-form-item>
      <a-form-item label="文章内容" name="content" v-if="formState.articleType === 0">
        <a-input v-model:value="formState.externalLink" placeholder="http://"></a-input>
      </a-form-item>
    </a-form>

    <a-row type="flex" justify="end">
      <a-button @click="onClose" class="cancel-btn" style="margin-right: 20px">取消</a-button>
      <a-button @click="onSubmit" class="cancel-btn" type="primary">确定</a-button>
    </a-row>
  </a-drawer>

  <!-- 添加弹出框 -->
  <a-modal
    v-model:visible="showHandlerTag"
    :title="tagWarningModel.title"
    @ok="handlerTag"
    @cancel="tagCancel"
  >
    <a-input type="text" v-model:value="tagText.labelName">
      <template #suffix>{{ tagText.labelName.length }}/20</template>
    </a-input>
  </a-modal>

  <!-- 删除标签弹出框 -->
  <warning-modal
    title="删除标签"
    content="删除标签"
    v-model:visible="tagWarningModel.isShow"
    @confirm="confirmDelTag"
  >
    标签删除后不可恢复，关联数据的关联关系将解除
  </warning-modal>
</template>
<script>
import { defineComponent, reactive, toRefs, ref, watch, toRaw } from 'vue';
import { message } from 'ant-design-vue';
import {
  apiGetArticleTagList,
  apiAddArticleTag,
  apiAddArticle,
  apiEditArticle,
  apiEditArticleTag,
  apiDelArticleTag,
} from '@/api/articleManage';
import WangEditor from '@/components/wang-editor';
import WarningModal from '@/components/warning-modal';

export default defineComponent({
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    editInfo: {
      type: Object,
      default: () => ({
        articleName: '',
        tags: [],
        articleType: 1,
        describeInfo: '',
        articleInfo: '',
      }),
    },
  },
  setup(props, { emit }) {
    const { editInfo } = toRefs(props); // 表单
    let isLoading = false;

    const title = ref('添加文章');
    const typeReadonly = ref(false);

    let formState = reactive({
      articleName: '',
      tags: [],
      articleType: 1,
      describeInfo: '',
      articleInfo: '',
      externalLink: '',
    }); // 表单信息

    watch(editInfo, key => {
      if (typeof key.id === 'number') {
        const form = toRaw(key);
        formState.articleName = form.articleName;
        formState.labelIds = form.labelIds;
        formState.id = form.id;
        formState.tags = form.labelList && form.labelList.map(item => item.id);
        tags.value = form.labelList;
        formState.articleType = form.articleType;
        formState.describeInfo = form.describeInfo;
        formState.articleInfo = form.articleInfo;
        wangEditor.value.setValue(form.articleInfo);
        formState.externalLink = form.externalLink;
      } else {
        confirmGetTagList();
        formState.articleName = '';
        formState.labelIds = '';
        formState.id = '';
        formState.tags = [];
        formState.articleType = 1;
        formState.describeInfo = '';
        formState.articleInfo = '';
        formState.editorValue = '';
        formState.externalLink = '';
      }
    });

    watch(
      () => formState.id,
      key => {
        title.value = typeof key === 'number' ? '编辑文章' : '添加文章';
        typeReadonly.value = typeof key === 'number';
      },
    );

    const formRef = ref(); // 表单组件

    const options = [
      // 文章类型配置
      {
        label: '平台文章',
        value: 1,
      },
      {
        label: '外部链接',
        value: 0,
      },
    ];

    const showHandlerTag = ref(false); // 显示添加标签
    const tagText = ref({
      labelName: '',
      id: '',
    }); // 标签描述

    // 表单校验规则
    const rules = reactive({
      articleName: [
        {
          required: true,
          message: '请输入文章标题',
          trigger: 'blur',
        },
        {
          min: 1,
          max: 45,
          message: '文章标题长度不能超过45位',
          trigger: 'blur',
        },
      ],
    });

    /**
     * 获取标签列表
     **/
    const tags = ref([]);
    const confirmGetTagList = keywords => {
      apiGetArticleTagList({ keywords }).then(res => {
        tags.value = res.list;
      });
    };
    confirmGetTagList();

    /**
     * 关闭弹窗
     **/
    const wangEditor = ref();
    const onClose = () => {
      emit('update:visible', false);
      formRef.value.resetFields();
      wangEditor.value.setValue('');
    };

    /**
     * 结构表单和处理字段
     **/
    const disposeForm = () => {
      let labelIds = '';
      formState.tags.forEach(item => {
        labelIds = labelIds + item + ',';
      });
      labelIds = labelIds.slice(0, -1);
      const { articleInfo, articleName, articleType, describeInfo, externalLink, id = '' } = toRaw(
        formState,
      );
      return { articleInfo, articleName, articleType, describeInfo, id, labelIds, externalLink };
    };

    /**
     * 提交表单
     **/
    const onSubmit = () => {
      formRef.value.validate().then(() => {
        if (isLoading) return;
        const form = disposeForm();
        if (typeof formState.id !== 'number') {
          confirmAddArticle(form);
        } else {
          confirmEditArticle(form);
        }
      });
    };

    /**
     * 确认编辑文章
     **/
    const confirmEditArticle = async form => {
      try {
        isLoading = true;
        await apiEditArticle(form);
        emit('get-list');
        onClose();
        message.success('编辑成功');
      } finally {
        isLoading = false;
      }
    };

    /**
     * 确认添加文章
     **/
    const confirmAddArticle = async form => {
      try {
        isLoading = true;
        await apiAddArticle(form);
        message.success('添加成功');
        onClose();
        emit('get-list');
      } finally {
        isLoading = false;
      }
    };

    /**
     * 关闭标签编辑框
     **/
    const tagWarningModel = reactive({ title: '', isShow: false });
    const tagCancel = () => {
      showHandlerTag.value = false;
      tagText.value = {
        labelName: '',
        id: '',
      };
    };

    /**
     * 删除标签
     **/
    const confirmDelTag = async () => {
      try {
        if (isLoading) return;
        isLoading = true;
        await apiDelArticleTag({ id: tagText.value.id });
        message.success('删除标签成功');
        tagWarningModel.isShow = false;
        confirmGetTagList();
      } finally {
        isLoading = false;
      }
    };

    /**
     * 确认添加标签
     **/
    const confirmAddTag = async () => {
      try {
        isLoading = true;
        await apiAddArticleTag({ labelName: tagText.value.labelName });
        message.success('添加标签成功');
        confirmGetTagList();
        tagCancel();
      } finally {
        isLoading = false;
      }
    };

    /**
     * 确认编辑标签
     **/
    const confirmApiEditTag = async () => {
      try {
        isLoading = true;
        await apiEditArticleTag({ labelName: tagText.value.labelName, id: tagText.value.id });
        message.success('编辑标签成功');
        tagCancel();
        confirmGetTagList();
      } finally {
        isLoading = false;
      }
    };

    const addTag = () => {
      showHandlerTag.value = true;
      tagWarningModel.title = '添加标签';
    };

    const editTag = text => {
      tagWarningModel.title = '编辑标签';
      showHandlerTag.value = true;
      tagText.value.labelName = text.labelName;
      tagText.value.id = text.id;
    };

    const delTag = tag => {
      tagText.value = tag;
      tagWarningModel.isShow = true;
    };

    /**
     * 请求操作标签
     **/
    const handlerTag = () => {
      if (isLoading) return;
      if (tagText.value.labelName.length > 20) {
        message.error('标签不能超过20');
      } else if (tagText.value.labelName.length === 0) {
        message.error('标签不能为空');
      } else {
        typeof tagText.value.id === 'number' ? confirmApiEditTag() : confirmAddTag();
      }
    };

    return {
      onClose,
      formRef,
      formState,
      rules,
      onSubmit,
      options,
      showHandlerTag,
      tagText,
      handlerTag,
      title,
      typeReadonly,
      tags,
      editTag,
      delTag,
      tagWarningModel,
      confirmDelTag,
      addTag,
      tagCancel,
      confirmGetTagList,
      wangEditor,
    };
  },
  emits: {
    'update:visible': null,
    'get-list': null,
  },
  components: {
    WarningModal,
    WangEditor,
  },
});
</script>

<style lang="less">
.article-info {
  .title {
    font-weight: 600;
    font-size: 14px;
  }
  .input-limit {
    color: #bfbfbf;
  }
  .creat-time {
    &-title {
      width: 88px;
      height: 40px;
      text-align: right;
    }
    &-content {
      margin-left: 10px;
    }
  }
  .describeInfo-tips {
    color: #666;
    font-size: 12px;
    line-height: 1.5;
  }
}
.article-info_textarea {
  position: relative;
  &::after {
    position: absolute;
    right: 5px;
    bottom: 0;
  }
}
.ant-select-item {
  position: relative;
  .ant-select-item-option-state {
    position: absolute;
    top: 6px;
    left: 2px;
  }
  .ant-select-item-option-content {
    padding: 0 5px;
  }
}
</style>
